package com.zyk.controller;

import com.zyk.vo.FinalResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * Created by Zyk on 2017/11/14.
 */
@Controller
public class LoginController {
    /**
     * 判断是否已经登陆，如果已经登陆直接跳转到index
     * @return
     */
    @GetMapping("/login")
    public String login(){
        if(SecurityUtils.getSubject().isAuthenticated()){
            return "index";
        }
        return "login";
    }

    /**
     * 登陆
     * @param username
     * @param captcha
     * @param password
     * @return
     */
    @PostMapping("login")
    public FinalResult login(String username, String captcha, String password){
        Subject subject = SecurityUtils.getSubject();
        try{
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            token.setRememberMe(true);//记住登陆记录1年
            subject.login(token);
        }catch (UnknownAccountException e1){
            throw new UnsupportedOperationException("用户名不存在");
        }catch (IncorrectCredentialsException e2){
            throw new IncorrectCredentialsException("密码错误");
        }
        return new FinalResult(true);
    }

    /**
     * 推出登录
     * @return
     */
    @RequestMapping("logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }
}
